package com.bang.study.lock;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @ClassName: FsLockDemo
 * @author: BANG
 * @Date: 2020/01/16 13:40
 * @Version: 1.0
 * @Modified By:
 * @Desc: 基于version的乐观锁并发控制
 * <p>
 * 全局锁的上锁实验
 */
public class FsLockDemo {

    public static void main(String[] args) throws IOException {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

        try {
            IndexResponse indexResponse = LockUtil.addGlobalLock(client);
            DeleteResponse deleteResponse = LockUtil.releaseGlobalLock(client);
            System.out.println(indexResponse);
            System.out.println(deleteResponse);

        } catch (VersionConflictEngineException e) {
            System.out.println("VersionConflictEngineException");
        } catch (Exception e) {
            System.out.println("Exception");
        }finally {
            client.close();
        }

    }
}
